using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;

namespace Cache
{

    
    public partial class frmOptions : Form
    {
        private string OldHomeName = null;
        private string OldHomeLat = null;
        private string OldHomeLon = null;
        private string[] tmp = new string[2];
        private string[] LatLon = new string[2];


        Options Opt = new Options();

        public frmOptions()
        {
            InitializeComponent();
        }

        private void cmdSaveOptions_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            //Save the Options that have been set in the options form.
            Options Options = new Options();

            Options.SaveOptions("GCUsername", txtGCUsername.Text);
            Options.SaveOptions("BackupEnable", chkBackupEnable.Checked.ToString());
            Options.SaveOptions("BackupPrompt", chkBackupPrompt.Checked.ToString());
            Options.SaveOptions("MapZoomLevel", cboMapZoomLevel.SelectedItem.ToString());
            Options.SaveOptions("BackupPath", txtBackupLocation.Text.ToString());
            Options.SaveOptions("CacheDispFound", chkCacheDispFound.Checked.ToString());
            Options.SaveOptions("CacheDispPlaced", chkCacheDispPlaced.Checked.ToString());
            Options.SaveOptions("CacheDispArchived", chkCacheDispArchived.Checked.ToString());

            string CacheColumn = null;
            
            //Get the value for all items in the list.
            for (int i = 0; i < chklstCacheColumns.Items.Count; i++)
            {
                CacheColumn = chklstCacheColumns.Items[i].ToString();
                CacheColumn = "CacheColumn-" + CacheColumn.Replace(" ", "_");
                
                Options.SaveOptions(CacheColumn, chklstCacheColumns.GetItemChecked(i).ToString());
            }
            
            Cursor.Current = Cursors.Arrow;
        }

        private void frmOptions_Load(object sender, EventArgs e)
        {
            //cboMapZoomLevel.Items.Add(new MapZoomLevelCBO("6000 Miles", "1"));

//            cmdFoundColor.BackColor = Color.FromArgb(-32645);

            
            Options Options = new Options();
            
            cmdFoundColor.BackColor = Color.FromArgb(Convert.ToInt32(Options.GetOption("CacheFoundColor")));
            cmdArchivedColor.BackColor = Color.FromArgb(Convert.ToInt32(Options.GetOption("CacheArchivedColor")));
            cmdPlacedColor.BackColor = Color.FromArgb(Convert.ToInt32(Options.GetOption("CachePlacedColor")));
            
            //Load all of the Map Zoom Levels that are available in VE.
            cboMapZoomLevel.Items.Add("6000 Miles");
            cboMapZoomLevel.Items.Add("3000 Miles");
            cboMapZoomLevel.Items.Add("1500 Miles");
            cboMapZoomLevel.Items.Add("700 Miles");
            cboMapZoomLevel.Items.Add("300 Miles");
            cboMapZoomLevel.Items.Add("150 Miles");
            cboMapZoomLevel.Items.Add("90 Miles");
            cboMapZoomLevel.Items.Add("40 Miles");
            cboMapZoomLevel.Items.Add("20 Miles");
            cboMapZoomLevel.Items.Add("10 Miles");
            cboMapZoomLevel.Items.Add("6 Miles");
            cboMapZoomLevel.Items.Add("3 Miles");
            cboMapZoomLevel.Items.Add("1.5 Miles");
            cboMapZoomLevel.Items.Add(".7 Miles");
            cboMapZoomLevel.Items.Add("600 Yards");
            cboMapZoomLevel.Items.Add("300 Yards");
            cboMapZoomLevel.Items.Add("150 Yards");
            cboMapZoomLevel.Items.Add("80 Yards");
            cboMapZoomLevel.Items.Add("40 Yards");


            cboGPSBrand.Items.Add("Garmin");
            cboGPSBrand.Items.Add("Magellen");

            cboGPSSerialPort.Items.Add("COM1");
            cboGPSSerialPort.Items.Add("COM2");
            cboGPSSerialPort.Items.Add("COM3");
            cboGPSSerialPort.Items.Add("COM4");
            cboGPSSerialPort.Items.Add("COM5");
            cboGPSSerialPort.Items.Add("COM6");

            //Load all of the home location from the DB
            GetHomeLocations();

            //Populate the entire form with the values stored in the database.
            chkBackupEnable.Checked = Convert.ToBoolean(Options.GetOption("BackupEnable"));
            chkBackupPrompt.Checked = Convert.ToBoolean(Options.GetOption("BackupPrompt"));
            txtGCUsername.Text = Options.GetOption("GCUsername");
            cboMapZoomLevel.SelectedItem = Options.GetOption("MapZoomLevel");
            txtBackupLocation.Text = Options.GetOption("BackupPath");

            chkCacheDispArchived.Checked = Convert.ToBoolean(Options.GetOption("CacheDispArchived"));
            chkCacheDispFound.Checked = Convert.ToBoolean(Options.GetOption("CacheDispFound"));
            chkCacheDispPlaced.Checked = Convert.ToBoolean(Options.GetOption("CacheDispPlaced"));
            
            //chklstCacheColumns.SelectedValue = Convert.ToBoolean(Options.GetOption("CacheColumn-Name"));
            
            chklstCacheColumns.Items.Add("Name");
            chklstCacheColumns.Items.Add("Desc");
            chklstCacheColumns.Items.Add("URL");
            chklstCacheColumns.Items.Add("URLName");
            chklstCacheColumns.Items.Add("Sym");
            chklstCacheColumns.Items.Add("PlacedBy");
            chklstCacheColumns.Items.Add("Owner");
            chklstCacheColumns.Items.Add("Type");
            chklstCacheColumns.Items.Add("Container");
            chklstCacheColumns.Items.Add("Difficulty");
            chklstCacheColumns.Items.Add("Terrain");
            chklstCacheColumns.Items.Add("Country");
            chklstCacheColumns.Items.Add("State");
            chklstCacheColumns.Items.Add("Short Description");
            chklstCacheColumns.Items.Add("Long Description");
            chklstCacheColumns.Items.Add("Encoded Hints");
            chklstCacheColumns.Items.Add("Latitude");
            chklstCacheColumns.Items.Add("Longitude");
            chklstCacheColumns.Items.Add("Available");
            chklstCacheColumns.Items.Add("Archived");
            chklstCacheColumns.Items.Add("Status");
            
            //Get the settings for the checkbox list from the database.
            chklstCacheColumns.SetItemChecked(0, Convert.ToBoolean(Options.GetOption("CacheColumn-Name")));
            chklstCacheColumns.SetItemChecked(1, Convert.ToBoolean(Options.GetOption("CacheColumn-Desc")));
            chklstCacheColumns.SetItemChecked(2, Convert.ToBoolean(Options.GetOption("CacheColumn-URL")));
            chklstCacheColumns.SetItemChecked(3, Convert.ToBoolean(Options.GetOption("CacheColumn-URLName")));
            chklstCacheColumns.SetItemChecked(4, Convert.ToBoolean(Options.GetOption("CacheColumn-Sym")));
            chklstCacheColumns.SetItemChecked(5, Convert.ToBoolean(Options.GetOption("CacheColumn-PlacedBy")));
            chklstCacheColumns.SetItemChecked(6, Convert.ToBoolean(Options.GetOption("CacheColumn-Owner")));
            chklstCacheColumns.SetItemChecked(7, Convert.ToBoolean(Options.GetOption("CacheColumn-Type")));
            chklstCacheColumns.SetItemChecked(8, Convert.ToBoolean(Options.GetOption("CacheColumn-Container")));
            chklstCacheColumns.SetItemChecked(9, Convert.ToBoolean(Options.GetOption("CacheColumn-Difficulty")));
            chklstCacheColumns.SetItemChecked(10, Convert.ToBoolean(Options.GetOption("CacheColumn-Terrain")));
            chklstCacheColumns.SetItemChecked(11, Convert.ToBoolean(Options.GetOption("CacheColumn-Country")));
            chklstCacheColumns.SetItemChecked(12, Convert.ToBoolean(Options.GetOption("CacheColumn-State")));
            chklstCacheColumns.SetItemChecked(13, Convert.ToBoolean(Options.GetOption("CacheColumn-Short_Description")));
            chklstCacheColumns.SetItemChecked(14, Convert.ToBoolean(Options.GetOption("CacheColumn-Long_Description")));
            chklstCacheColumns.SetItemChecked(15, Convert.ToBoolean(Options.GetOption("CacheColumn-Encoded_Hints")));
            chklstCacheColumns.SetItemChecked(16, Convert.ToBoolean(Options.GetOption("CacheColumn-Latitude")));
            chklstCacheColumns.SetItemChecked(17, Convert.ToBoolean(Options.GetOption("CacheColumn-Longitude")));
            chklstCacheColumns.SetItemChecked(18, Convert.ToBoolean(Options.GetOption("CacheColumn-Available")));
            chklstCacheColumns.SetItemChecked(19, Convert.ToBoolean(Options.GetOption("CacheColumn-Archived")));
            chklstCacheColumns.SetItemChecked(20, Convert.ToBoolean(Options.GetOption("CacheColumn-Status")));
            
            //Get all GPSr settings.
            cboGPSSerialPort.SelectedItem = Opt.GetOption("GPSComPort");
            cboGPSBrand.SelectedItem = Opt.GetOption("GPSBrand");
            if (Opt.GetOption("GPSConnType") == "Serial")
            {
                rdoGPSSerial.Checked = true;
            }

            if (Opt.GetOption("GPSConnType") == "USB")
            {
                rdoGPSUSB.Checked = true;
            }
        }

        private void GetHomeLocations()
        {
            lstHomeLocations.Items.Clear();
            SQLiteConnection conn = new SQLiteConnection("data source=" + Application.StartupPath + @"\GeoCaches.db");

            SQLiteDataReader rdr = null;
            SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM tblHomeLocations", conn);

            conn.Open();
            try
            {
                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    lstHomeLocations.Items.Add(rdr["Name"] + ": " + rdr["Lat"] + ", " + rdr["Lon"]); 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            rdr.Close();
            conn.Close();

        }

        private void cmdHomeAdd_Click(object sender, EventArgs e)
        {
            SQLiteConnection conn = new SQLiteConnection("data source=" + Application.StartupPath + @"\GeoCaches.db");
            SQLiteDataReader rdr = null;

            conn.Open();

            string mySQL;

            mySQL = "INSERT INTO tblHomeLocations(Name, Lat, Lon) VALUES ('" + txtHomeName.Text + "', '" + txtHomeLat.Text + "', '" + txtHomeLon.Text + "')";
            SQLiteCommand cmd = new SQLiteCommand(mySQL, conn);

            try
            {
                rdr = cmd.ExecuteReader();

                rdr.Close();
                conn.Close();

                txtHomeName.Clear();
                txtHomeLon.Clear();
                txtHomeLat.Clear();
                GetHomeLocations();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + "\r\n\r\nSQL: " + mySQL);
            }


        }

        private void lstHomeLocations_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Check to make sure that an item has actuall been selected.
            if (lstHomeLocations.SelectedIndex >= 0)
            {

                cmdHomeModify.Visible = true;
                cmdHomeDefault.Visible = true;

                tmp = lstHomeLocations.SelectedItem.ToString().Split(':');

                LatLon = tmp[1].Split(',');

            }

        }

        private void cmdHomeUpdate_Click(object sender, EventArgs e)
        {
            
            cmdHomeUpdate.Visible = false;
            cmdHomeAdd.Visible = true;

            SQLiteConnection conn = new SQLiteConnection("data source=" + Application.StartupPath + @"\GeoCaches.db");

            conn.Open();
            string mySQL;

            mySQL = "UPDATE tblHomeLocations SET ";
            mySQL += "Name = '" + txtHomeName.Text + "', Lat = '" + txtHomeLat.Text + "', Lon = '" + txtHomeLon.Text + "'";
            mySQL += " WHERE Name = '" + OldHomeName + "' AND Lat = '" + OldHomeLat + "' AND Lon = '" + OldHomeLon + "'";

            SQLiteCommand cmd = new SQLiteCommand(mySQL, conn);

            try
            {
                cmd.ExecuteNonQuery();
                GetHomeLocations();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + "\r\n\r\nSQL Statement: " + mySQL);
            }
            txtHomeLat.Clear();
            txtHomeLon.Clear();
            txtHomeName.Clear();

        }

        private void cmdHomeModify_Click(object sender, EventArgs e)
        {
            cmdHomeDefault.Visible = false;
            cmdHomeModify.Visible = false;

            txtHomeName.Text = tmp[0].ToString();

            txtHomeLat.Text = LatLon[0].ToString().Replace(" ", "");
            txtHomeLon.Text = LatLon[1].ToString().Replace(" ", "");

            OldHomeName = tmp[0].ToString();
            OldHomeLat = LatLon[0].ToString().Replace(" ", "");
            OldHomeLon = LatLon[1].ToString().Replace(" ", "");

            cmdHomeAdd.Visible = false;
            cmdHomeUpdate.Visible = true;
            //MessageBox.Show();


        }

        private void cmdHomeDefault_Click(object sender, EventArgs e)
        {
            SQLiteConnection conn = new SQLiteConnection("data source=" + Application.StartupPath + @"\GeoCaches.db");

            SQLiteDataReader rdr = null;
            string mySQL = null;
            mySQL = "SELECT * FROM tblHomeLocations WHERE Name = '" + tmp[0].ToString().Replace(" ", "") + "' AND Lat = '" + LatLon[0].ToString().Replace(" ", "") + "' AND Lon = '" + LatLon[1].ToString().Replace(" ", "") + "'";

            SQLiteCommand cmd = new SQLiteCommand(mySQL, conn);

            MessageBox.Show(mySQL);
            conn.Open();

            string HomeID = null;

            try
            {
                rdr = cmd.ExecuteReader();

                if (rdr.HasRows == true)
                {
                    HomeID = rdr["HomeID"].ToString();
                }
                else
                {                    
                    MessageBox.Show("Oops!  I messed up, I have no record of that transaction. \r\nTell the guy who wrote this to look at frmOptions.cs \r\nThere is not ID associated with the HomeID", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                rdr.Close();
                conn.Close();
                Options Options = new Options();
                Options.SaveOptions("HomeLocation", HomeID);

            }//End Try
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }//End Catch

            rdr.Close();
            conn.Close();
        }


        private void cmdBackupBrowse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog FBD1 = new FolderBrowserDialog();
            //FBD1.RootFolder = Application.StartupPath + @"\Backup";
            FBD1.SelectedPath = Application.StartupPath;
            FBD1.ShowNewFolderButton = true;

            if (FBD1.ShowDialog() == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                txtBackupLocation.Text = FBD1.SelectedPath.ToString();
                Cursor.Current = Cursors.Arrow;
            }
        }

        private void cmdCacheSelAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < chklstCacheColumns.Items.Count; i++)
            {
                chklstCacheColumns.SetItemChecked(i, true);
                //chklstCacheColumns.Select(i);
            }
        }

        private void cmdFoundColor_Click(object sender, EventArgs e)
        {
            ColorDialog CD = new ColorDialog();
            Options Opt = new Options();

            if (CD.ShowDialog() == DialogResult.OK)
            {
                Opt.SaveOptions("CacheFoundColor", CD.Color.ToArgb().ToString());
                cmdFoundColor.BackColor = Color.FromArgb(Convert.ToInt32(CD.Color.ToArgb()));
            }
        }

        private void cmdPlacedColor_Click(object sender, EventArgs e)
        {
            ColorDialog CD = new ColorDialog();
            Options Opt = new Options();

            if (CD.ShowDialog() == DialogResult.OK)
            {
                Opt.SaveOptions("CachePlacedColor", CD.Color.ToArgb().ToString());
                cmdPlacedColor.BackColor = Color.FromArgb(Convert.ToInt32(CD.Color.ToArgb()));
            }
        }

        private void cmdArchivedColor_Click(object sender, EventArgs e)
        {
            ColorDialog CD = new ColorDialog();
            Options Opt = new Options();

            if (CD.ShowDialog() == DialogResult.OK)
            {
                Opt.SaveOptions("CacheArchivedColor", CD.Color.ToArgb().ToString());
                cmdArchivedColor.BackColor = Color.FromArgb(Convert.ToInt32(CD.Color.ToArgb()));
            }
        }

        private void rdoGPSSerial_CheckedChanged(object sender, EventArgs e)
        {

            if (rdoGPSSerial.Checked == true)
            {
                cboGPSSerialPort.Enabled = true;
                Opt.SaveOptions("GPSConnType", "Serial");
            }
            else
                cboGPSSerialPort.Enabled = false;
            
        }

        private void rdoGPSUSB_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoGPSSerial.Checked == true)
            {
                cboGPSSerialPort.Enabled = true;
                Opt.SaveOptions("GPSConnType", "USB");
            }

            else
                cboGPSSerialPort.Enabled = false;
            
        }

        private void cboGPSSerialPort_SelectedIndexChanged(object sender, EventArgs e)
        {
            Opt.SaveOptions("GPSComPort", cboGPSSerialPort.SelectedItem.ToString());
        }

        private void cboGPSBrand_SelectedIndexChanged(object sender, EventArgs e)
        {
            Opt.SaveOptions("GPSBrand", cboGPSBrand.SelectedItem.ToString());
        }

    }
}